﻿using Barcode_Project.Entity;
using Flurl;
using Flurl.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using System.Data;
using Newtonsoft.Json;
using DevExpress.XtraEditors;
using System.Threading;
using System.Collections.ObjectModel;
using System.Windows.Forms;
using System.Collections;
using Barcode_Project.Local;
using Newtonsoft.Json.Linq;
using System.Configuration;
using static System.Net.WebRequestMethods;
using System.Security.Policy;
using System.Diagnostics;
using System.Net;
using DevExpress.XtraLayout.Customization;
using System.Web;
using System.Management;
using iTextSharp.text;

namespace Barcode_Project.Network
{
    public partial class RemoteRequest
    {
        ILog _log;
        HttpAgreement http;
        public RemoteRequest()
        {
            _log = LogManager.GetLogger(GetType().Name);
            http = new HttpAgreement();
        }
        // 从网页获取的基础请求地址
        public static string serverUrl { get; set; } = "http://192.168.1.43:8080/";
        //public static string serverUrl { get; set; } = "http://localhost:16989/";

        string baseCode = WebsiteInfo.baseCode;

        // 获取存货筛选列表 请求地址
        public List<FilteredProduct> GetProductList(string proCode, string proName, string spec)
        {
            var list = new List<FilteredProduct>();

            try
            {
                var uploadDic = new Dictionary<string, string>();

                uploadDic["proCode"] = proCode;
                uploadDic["proName"] = proName;
                uploadDic["spec"] = spec;
                uploadDic["baseCode"] = WebsiteInfo.baseCode;

                string url = CommonMethods.APIUrl() + "GetProductList";
                var info = http.HttpPost(url, JsonConvert.SerializeObject(uploadDic));

                if (string.IsNullOrWhiteSpace(info))
                {
                    XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return list;
                }

                var obj = JsonConvert.DeserializeObject<JObject>(info);

                if (bool.Parse(obj["result"].ToString()))
                {
                    list = JsonConvert.DeserializeObject<List<FilteredProduct>>(obj["data"].ToString());
                }
                else
                {
                    XtraMessageBox.Show(obj["message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return list;
                }

                //list = serverUrl
                //.AppendPathSegment("bar")
                //.AppendPathSegment("GetProductList")
                //.SetQueryParams(new { proCode, proName, spec, baseCode })
                //.GetJsonAsync<List<FilteredProduct>>().Result;
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }

            return list;
        }

        // 获取仓库列表
        public List<ItemSelector> GetWarehouseList()
        {
            var list = new List<ItemSelector>();
            try
            {
                var uploadDic = new Dictionary<string, string>();
                uploadDic["baseCode"] = baseCode;

                string url = CommonMethods.APIUrl() + "GetWarehouseList";
                var info = http.HttpPost(url, JsonConvert.SerializeObject(uploadDic));

                if (string.IsNullOrWhiteSpace(info))
                {
                    XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return list;
                }

                var obj = JsonConvert.DeserializeObject<JObject>(info);

                if (bool.Parse(obj["result"].ToString()))
                {
                    list = JsonConvert.DeserializeObject<List<ItemSelector>>(obj["data"].ToString());
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }
            return list;
        }
        // 获取机台列表
        public List<ItemSelector> GetMachineList()
        {
            var list = new List<ItemSelector>();
            try
            {
                var uploadDic = new Dictionary<string, string>();
                uploadDic["baseCode"] = baseCode;

                string url = CommonMethods.APIUrl() + "GetMachineList";
                var info = http.HttpPost(url, JsonConvert.SerializeObject(uploadDic));

                if (string.IsNullOrWhiteSpace(info))
                {
                    XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return list;
                }

                var obj = JsonConvert.DeserializeObject<JObject>(info);

                if (bool.Parse(obj["result"].ToString()))
                {
                    list = JsonConvert.DeserializeObject<List<ItemSelector>>(obj["data"].ToString());
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }
            return list;
        }
        // 保存板架
        public void SaveBanJia(Dictionary<string,string> uploadDic)
        {
            try
            {
                //var uploadDic = new Dictionary<string, string>();
                uploadDic["baseCode"] = baseCode;

                string url = CommonMethods.APIUrl() + "SaveBanJia";
                var info = http.HttpPost(url, JsonConvert.SerializeObject(uploadDic));

                if (string.IsNullOrWhiteSpace(info))
                {
                    XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }

                var obj = JsonConvert.DeserializeObject<JObject>(info);

                if (bool.Parse(obj["result"].ToString()))
                {

                }
                else
                {
                    XtraMessageBox.Show("保存板架失败" + obj["message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }
        }
        // 期初打码
        public DataTable InitPrint(string json)
        {
            var dt = new DataTable();
            try
            {
                var result = serverUrl
                    .AppendPathSegment("bar")
                    .AppendPathSegment("InitPrint")
                    .SetQueryParams(new { json })
                    .GetJsonAsync<ReturnResult>().Result;

                if (result.Result)
                {
                    dt = JsonConvert.DeserializeObject<DataTable>(result.Data.ToString());
                }
                else
                {
                    dt = null;

                    XtraMessageBox.Show(result.Message);
                }

            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }

            return dt;
        }
        // 获取生产计划和工序下 已打印的条码
        public List<PrintedBarcode> GetPrintedBarCodes_ByPlCode_GxCode(string plCode, string gxCode)
        {
            HttpAgreement http = new HttpAgreement();
            List<PrintedBarcode> dList = new List<PrintedBarcode>();
            var dic = new Dictionary<string, string>();
            dic["plCode"] = plCode;
            dic["gxCode"] = gxCode;
            string url = ConfigurationManager.AppSettings["APIUrl"].ToString() + "GetPlanPrintBars";
            var info = http.PostJson(url, JsonConvert.SerializeObject(dic));
            if (string.IsNullOrWhiteSpace(info))
            {
                XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            }
            var obj = JsonConvert.DeserializeObject<JObject>(info);
            if (bool.Parse(obj["result"].ToString()))
            {

                return JsonConvert.DeserializeObject<List<PrintedBarcode>>(obj["data"].ToString());
            }
            else
            {
                XtraMessageBox.Show(obj["message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            }
            return dList;
        }
        // 生产打码查询 关联条码
        public List<RelativeBarCode> GetRelativeBarCodes(string plCode, string gxCode)
        {
            var list = new List<RelativeBarCode>();

            try
            {
                var uploadDic = new Dictionary<string, string>();

                uploadDic["plCode"] = plCode;
                uploadDic["gxCode"] = gxCode;

                string url = CommonMethods.APIUrl() + "GetRelativeBarCodes";
                var info = http.HttpPost(url, JsonConvert.SerializeObject(uploadDic));

                if (string.IsNullOrWhiteSpace(info))
                {
                    XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return list;
                }

                var obj = JsonConvert.DeserializeObject<JObject>(info);

                if (bool.Parse(obj["result"].ToString()))
                {
                    list = JsonConvert.DeserializeObject<List<RelativeBarCode>>(obj["data"].ToString());
                }

                //list = serverUrl
                //    .AppendPathSegment("bar")
                //    .AppendPathSegment("GetRelativeBarCodes")
                //    .SetQueryParams(new { plCode, gxCode })
                //    .GetJsonAsync<List<RelativeBarCode>>().Result;
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }

            return list;
        }
        // 生产打码利用扫码枪录入条码，检查条码可用性并返回
        public UsedBarCode GetScannedBarCodeInfo(string barCode, string plCode, string gxCode)
        {
            var bar = new UsedBarCode();
            try
            {
                var uploadDic = new Dictionary<string, string>();

                uploadDic["barCode"] = barCode;
                uploadDic["plCode"] = plCode;
                uploadDic["gxCode"] = gxCode;

                string url = CommonMethods.APIUrl() + "GetScannedBarCodeInfo";
                var info = http.HttpPost(url, JsonConvert.SerializeObject(uploadDic));

                if (string.IsNullOrWhiteSpace(info))
                {
                    XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return bar;
                }

                var obj = JsonConvert.DeserializeObject<JObject>(info);

                if (bool.Parse(obj["result"].ToString()))
                {
                    bar = JsonConvert.DeserializeObject<UsedBarCode>(obj["data"].ToString());
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }
            return bar;
        }
        // 生产计划打印
        public DataTable PlanPrint(string json)
        {
            var dt = new DataTable();
            try
            {
                var result = serverUrl
                    .AppendPathSegment("Services")
                    .AppendPathSegment("PlanPrint")
                    .SetQueryParams(new { json })
                    .GetJsonAsync<ReturnResult>().Result;

                if (result.Result)
                {
                    dt = JsonConvert.DeserializeObject<DataTable>(result.Data.ToString());
                }
                else
                {
                    dt = null;

                    XtraMessageBox.Show(result.Message);
                }

            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }

            return dt;
        }
        // 采购打印
        public DataTable PurchasePrint(string json)
        {
            var dt = new DataTable();
            try
            {
                var result = serverUrl
                    .AppendPathSegment("bar")
                    .AppendPathSegment("PurchaseInPrint")
                    .SetQueryParams(new { json })
                    .GetJsonAsync<ReturnResult>().Result;

                if (result.Result)
                {
                    dt = JsonConvert.DeserializeObject<DataTable>(result.Data.ToString());
                }
                else
                {
                    dt = null;

                    XtraMessageBox.Show(result.Message);
                }
            }
            catch (Exception ex)
            {

            }
            return dt;
        }
        // 根据采购订单号和子表行号，获取已打印条码
        public List<PrintedBarcode> GetPrintedBarcodes_ByRdrecord01_cCode_iRowNo(string cCode, string irowno)
        {
            var list = new List<PrintedBarcode>();
            try
            {
                list = serverUrl
                    .AppendPathSegment("bar")
                    .AppendPathSegment("GetPrintedBarcodes_ByRdrecord01_cCode_iRowNo")
                    .SetQueryParams(new { cCode, irowno })
                    .GetJsonAsync<List<PrintedBarcode>>().Result;
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }
            return list;
        }
        /// <summary>
        /// 获取计划工序关联条码
        /// </summary>
        /// <param name="plCode"></param>
        /// <param name="gxCode"></param>
        /// <returns></returns>
        public List<NeedCutBarCode> GetPlanGxBarCodes(string plCode, string gxCode, string spec)
        {
            HttpAgreement http = new HttpAgreement();
            List<NeedCutBarCode> dList = new List<NeedCutBarCode>();
            var dic = new Dictionary<string, string>();
            dic["plCode"] = plCode;
            dic["gxCode"] = gxCode;
            dic["spec"] = spec;
            string url = ConfigurationManager.AppSettings["APIUrl"].ToString() + "GetPlanGxBarCodes";
            var info = http.PostJson(url, JsonConvert.SerializeObject(dic));
            if (string.IsNullOrWhiteSpace(info))
            {
                XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            }
            var obj = JsonConvert.DeserializeObject<JObject>(info);
            if (bool.Parse(obj["result"].ToString()))
            {
                dList = JsonConvert.DeserializeObject<List<NeedCutBarCode>>(obj["data"].ToString());
            }
            else
            {
                XtraMessageBox.Show(obj["message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            }
            return dList;
        }
        // 分切条码的方法
        public DataTable CutPrint(string json)
        {
            var dt = new DataTable();
            try
            {
                var result = serverUrl
                    .AppendPathSegment("bar")
                    .AppendPathSegment("CutPrint")
                    .SetQueryParams(new { json })
                    .GetJsonAsync<ReturnResult>().Result;

                if (result.Result)
                {
                    dt = JsonConvert.DeserializeObject<DataTable>(result.Data.ToString());
                }
                else
                {
                    dt = null;

                    XtraMessageBox.Show(result.Message);
                }

            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }

            return dt;
        }

        public void OpenWebPage(string urlPath)
        {
            urlPath = serverUrl + urlPath;

            System.Diagnostics.Process.Start(urlPath);
        }

        public List<PrintedBarcode> GetCuttedBarcodes(string plCode)
        {
            var list = new List<PrintedBarcode>();
            try
            {
                list = serverUrl
                    .AppendPathSegment("bar")
                    .AppendPathSegment("GetCuttedBarcodes")
                    .SetQueryParams(new { plCode })
                    .GetJsonAsync<List<PrintedBarcode>>().Result;
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }
            return list;
        }
        // 原辅料重新打码 自动提示方法
        public async Task<ICollection> BarCodeAutoSuggest(string input, CancellationToken cancel)
        {
            var list = new List<string>();

            try
            {
                var uploadDic = new Dictionary<string, string>();
                uploadDic["text"] = input;

                string url = CommonMethods.APIUrl() + "MatAuxRePrint_AutoSuggest";

                var task = Task.Run(() => { return http.HttpPost(url, JsonConvert.SerializeObject(uploadDic)); });

                var info = await task;

                if (string.IsNullOrWhiteSpace(info))
                {
                    XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return null;
                }

                var obj = JsonConvert.DeserializeObject<JObject>(info);

                if (bool.Parse(obj["result"].ToString()))
                {
                    list = JsonConvert.DeserializeObject<List<string>>(obj["data"].ToString());
                }
                else
                {
                    XtraMessageBox.Show(obj["message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return null;
                }

                //list = await serverUrl
                //   .AppendPathSegment("bar")
                //   .AppendPathSegment("MatAuxRePrint_AutoSuggest")
                //   .SetQueryParams(new { input })
                //   .GetJsonAsync<List<string>>();
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }

            return list;
        }
        // 原辅料重新打码 获取旧条码信息
        public PrintedBarcode GetOldBarCodeInfo(string barCode)
        {
            var bar = new PrintedBarcode();

            try
            {
                bar = serverUrl
                    .AppendPathSegment("bar")
                    .AppendPathSegment("GetOldBarCodeInfo")
                    .SetQueryParams(new { barCode })
                    .GetJsonAsync<PrintedBarcode>().Result;
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }

            return bar;
        }

        public DataTable MatAuxRePrint(string json)
        {
            var dt = new DataTable();
            try
            {
                var result = serverUrl
                    .AppendPathSegment("bar")
                    .AppendPathSegment("MatAuxRePrint")
                    .SetQueryParams(new { json })
                    .GetJsonAsync<ReturnResult>().Result;
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }
            return dt;
        }
        // 获取版辊自动提示
        public async Task<ICollection> PlateRollerAutoSuggest(string input, CancellationToken cancel)
        {
            var list = new List<string>();

            try
            {
                var uploadDic = new Dictionary<string, string>();
                uploadDic["text"] = input;

                string url = CommonMethods.APIUrl() + "PlateRoller_AutoSuggest";

                var task = Task.Run(() => { return http.HttpPost(url, JsonConvert.SerializeObject(uploadDic)); });

                var info = await task;

                if (string.IsNullOrWhiteSpace(info))
                {
                    XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return null;
                }

                var obj = JsonConvert.DeserializeObject<JObject>(info);

                if (bool.Parse(obj["result"].ToString()))
                {
                    list = JsonConvert.DeserializeObject<List<string>>(obj["data"].ToString());
                }
                else
                {
                    XtraMessageBox.Show(obj["message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return null;
                }

                //list = await serverUrl
                //   .AppendPathSegment("bar")
                //   .AppendPathSegment("PlateRoller_AutoSuggest")
                //   .SetQueryParams(new { input })
                //   .GetJsonAsync<List<string>>();
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }

            return list;
        }
        // 获取版支信息
        public Dictionary<string, string> GetPlateRollerBranchInfo(string byBarCode)
        {
            var v_pri = new Dictionary<string, string>();

            try
            {
                var uploadDic = new Dictionary<string, string>();
                uploadDic["byBarCode"] = byBarCode;

                var json = JsonConvert.SerializeObject(uploadDic);

                string url = CommonMethods.APIUrl() + "GetPlateRollerInfo";
                var info = http.HttpPost(url, json);

                if (string.IsNullOrWhiteSpace(info))
                {
                    XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return null;
                }

                var obj = JsonConvert.DeserializeObject<JObject>(info);

                if (bool.Parse(obj["result"].ToString()))
                {
                    v_pri = JsonConvert.DeserializeObject<Dictionary<string, string>>(obj["data"].ToString());

                }
                else
                {
                    XtraMessageBox.Show(obj["message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return null;
                }

                //v_pri = serverUrl
                //    .AppendPathSegment("bar")
                //    .AppendPathSegment("GetPlateRollerInfo")
                //    .SetQueryParams(new { byBarCode })
                //    .GetJsonAsync<ViewPlateRollerInfo>().Result;
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }

            return v_pri;
        }

        public List<ProductSelectItem> SearchInventories(Dictionary<string, string> filterDic)
        {
            HttpAgreement http = new HttpAgreement();
            List<ProductSelectItem> dList = new List<ProductSelectItem>();

            string url = ConfigurationManager.AppSettings["APIUrl"].ToString() + "SearchInventories";
            var info = http.PostJson(url, JsonConvert.SerializeObject(filterDic));
            if (string.IsNullOrWhiteSpace(info))
            {
                XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            var obj = JsonConvert.DeserializeObject<JObject>(info);
            if (bool.Parse(obj["result"].ToString()))
            {
                dList = JsonConvert.DeserializeObject<List<ProductSelectItem>>(obj["data"].ToString());
            }
            else
            {
                XtraMessageBox.Show(obj["message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return dList;
        }

        public List<VendorSelectItem> SearchVendors(Dictionary<string, string> filterDic)
        {
            HttpAgreement http = new HttpAgreement();
            List<VendorSelectItem> dList = new List<VendorSelectItem>();

            string url = ConfigurationManager.AppSettings["APIUrl"].ToString() + "SearchVendors";
            var info = http.PostJson(url, JsonConvert.SerializeObject(filterDic));
            if (string.IsNullOrWhiteSpace(info))
            {
                XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            var obj = JsonConvert.DeserializeObject<JObject>(info);
            if (bool.Parse(obj["result"].ToString()))
            {
                dList = JsonConvert.DeserializeObject<List<VendorSelectItem>>(obj["data"].ToString());
            }
            else
            {
                XtraMessageBox.Show(obj["message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return dList;
        }

        public List<UserSelectItem> SearchUsers(Dictionary<string, string> filterDic)
        {
            HttpAgreement http = new HttpAgreement();
            List<UserSelectItem> dList = new List<UserSelectItem>();

            string url = ConfigurationManager.AppSettings["APIUrl"].ToString() + "SearchUsers";
            var info = http.PostJson(url, JsonConvert.SerializeObject(filterDic));

            if (string.IsNullOrWhiteSpace(info))
            {
                XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            var obj = JsonConvert.DeserializeObject<JObject>(info);
            if (bool.Parse(obj["result"].ToString()))
            {
                dList = JsonConvert.DeserializeObject<List<UserSelectItem>>(obj["data"].ToString());
            }
            else
            {
                XtraMessageBox.Show(obj["message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            return dList;
        }
        public void UpdateProgram()
        {
            //@= "powershell -command \"Invoke-WebRequest -URI \"http://localhost:3720/Service/GetPrintExcel?filename=2023_08_03_16_57_52_380.xls\" -OutFile \"C:/Excels/1.xls\";start-process -filepath \"C:/Excels/1.xls\" -verb print;\""

            // 获取当前文件夹位置
            var folder = ConfigurationManager.AppSettings["program_path"].ToString();
            // 原始文件名称
            var oriFileName = folder + "BarCode-Project.exe";
            // 新文件名称
            var newFileName = folder + "BarCode-Project-new.exe";

            // 获取下载文件网址APIUrl
            var downloadUrl = ConfigurationManager.AppSettings["APIUrl"].ToString() + "GetLastPrintClient";

            //Invoke - WebRequest - URI \"http://localhost:3720/Service/GetPrintExcel?filename=2023_08_03_16_57_52_380.xls\" -OutFile \"C:/Excels/1.xls\";
            var downloadScirpt = "Invoke - WebRequest - URI \"{0}\" -OutFile \"{1}\"";
            downloadScirpt = string.Format(downloadUrl, downloadScirpt, newFileName);

            // 重命名新文件并清理旧文件
            // Remove-Item -Path C:\Test\hidden-RO-file.txt -Force
            //Rename-Item -Path "c:\logfiles\daily_file.txt" -NewName "monday_file.txt"
            var deleteOriFileScript = "Remove-Item -Path \"{0}\" -Force";
            deleteOriFileScript = string.Format(deleteOriFileScript, oriFileName);

            var renameNewFileScript = "Rename-Item -Path \"{0}\" -NewName \"{1}\"";
            renameNewFileScript = string.Format(renameNewFileScript, newFileName, oriFileName);

            // 启动客户端并传递参数
            string[] args = Environment.GetCommandLineArgs();
            var arg1 = args[1];
            arg1 = HttpUtility.UrlDecode(arg1);

            var reOpenProgramScript = "start-process -filepath \"{0}\" -ArgumentList \"{1}\"";
            reOpenProgramScript = string.Format(reOpenProgramScript, oriFileName, arg1);

            var powerShellScript = $@"{downloadScirpt};{deleteOriFileScript};{renameNewFileScript};{reOpenProgramScript}";

            // /C 是立刻结束 /K 是不结束
            var startScript = $@"/K powershell.exe -command '{powerShellScript}'";

            _log.Info(startScript);

            System.Diagnostics.Process process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            //startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            startInfo.FileName = "cmd.exe";
            startInfo.Arguments = startScript;
            process.StartInfo = startInfo;
            process.Start();

        }

        public void UpdateCmdProgram()
        {
            var updateProgramFullPath = ConfigurationManager.AppSettings["UpdaterPath"];

            StartNewProgramByCreateFlags("cmd /C " + updateProgramFullPath + " " + Environment.GetCommandLineArgs()[1]);

            Application.Exit();
        }

        void StartNewProgramByCreateFlags(string exePath)
        {
            using (var managementClass = new ManagementClass("Win32_Process"))
            {
                var processInfo = new ManagementClass("Win32_ProcessStartup");

                processInfo.Properties["CreateFlags"].Value = 0x00000008;
                processInfo.Properties["ShowWindow"].Value = 0x00000001;

                var inParameters = managementClass.GetMethodParameters("Create");
                //inParameters["CommandLine"] = "notepad.exe";
                inParameters["CommandLine"] = exePath;
                inParameters["ProcessStartupInformation"] = processInfo;

                var result = managementClass.InvokeMethod("Create", inParameters, null);
                if ((result != null) && ((uint)result.Properties["ReturnValue"].Value != 0))
                {
                    Console.WriteLine("Process ID: {0}", result.Properties["ProcessId"].Value);
                }
            }
        }

        public DataTable GetReBarInfo(string barCode)
        {
            HttpAgreement http = new HttpAgreement();
            List<ProductSelectItem> dList = new List<ProductSelectItem>();

            DataTable dt = null;

            string url = ConfigurationManager.AppSettings["APIUrl"].ToString() + "GetReBarInfo";

            var dic = new Dictionary<string, string>();
            dic["barCode"] = barCode;

            var info = http.PostJson(url, JsonConvert.SerializeObject(dic));

            if (string.IsNullOrWhiteSpace(info))
            {
                XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            var obj = JsonConvert.DeserializeObject<JObject>(info);

            if (bool.Parse(obj["result"].ToString()))
            {
                dt = JsonConvert.DeserializeObject<DataTable>(obj["data"].ToString());
            }
            else
            {
                XtraMessageBox.Show(obj["message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return dt;
        }

        public DataTable GetPlanGxInfo(string plCode, string gxCode)
        {
            HttpAgreement http = new HttpAgreement();
            List<ProductSelectItem> dList = new List<ProductSelectItem>();

            DataTable dt = null;

            string url = ConfigurationManager.AppSettings["APIUrl"].ToString() + "GetPlanTechnologyForm";

            var dic = new Dictionary<string, string>();
            dic["plCode"] = plCode;
            dic["gxCode"] = gxCode;

            var info = http.PostJson(url, JsonConvert.SerializeObject(dic));

            if (string.IsNullOrWhiteSpace(info))
            {
                XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            var obj = JsonConvert.DeserializeObject<JObject>(info);

            if (bool.Parse(obj["result"].ToString()))
            {
                dt = JsonConvert.DeserializeObject<DataTable>(obj["data"].ToString());
            }
            else
            {
                XtraMessageBox.Show(obj["message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return dt;
        }

    }


}
